import wepy from 'wepy';

// let env = 'home';
let env = 'company';
// let env = 'alpha';

function getUrl(uri) {
  let url = '';
  switch (env) {
    case 'home':
      url = 'http://local.huanbao.io/api/' + uri;
      break;
    case 'alpha':
      url = 'https://huanbao.xiaomlove.com/api/' + uri;
      break;
    case 'company':
      url = 'http://huanbao.local:8080/api/' + uri;
      break;
    default: 
      throw new Error("invalid env: " + env);
      break;
  }
  return url; 
}

async function request(method, uri, params = '', appendHeaders = {}, token = true, tryTimes = 0) {
  let ID = (new Date()).getTime();
  let __params = Object.assign({}, params);
  if (__params.__resource_id) {
    uri += "/" + __params.__resource_id;
    delete __params.__resource_id;
  }
  delete __params.has_more;
  let url = getUrl(uri);
  let headers = {
    "Content-Type": "application/json", 
    "Accept": "application/json"
  };
  if (token) {
    let app = wepy.$instance;
    if (app.globalData && app.globalData.userInfo) {
      let userInfo = app.globalData.userInfo;
      let accessToken = userInfo.auth.access_token;
      headers.Authorization = "Bearer " + accessToken;
    }
  }
  let options = {
    url: url,
    data: __params,
    header: headers,
    method: method.toUpperCase()
  };
  console.log(`request  --- ${ID} --- `, options);
  let response = await wepy.request(options);
  console.log(`response --- ${ID} --- `, response);

  let statusCode = response.statusCode;
  if (statusCode == 401) {
    let jscodeRes = await wepy.login();
    let loginRes = await request('post', 'login/weixin', jscodeRes, null, false, true);
    if (tryTimes < 3 && loginRes.ret == 0 && loginRes.data.auth) {
      tryTimes++;
      wepy.$instance.globalData.userInfo = loginRes.data;
      return request(method, uri, __params, appendHeaders, token, tryTimes);
    } else {
      wepy.showToast({
        title: (loginRes.msg || "登录失败") + "(" + tryTimes + ")",
        icon: "none",
        duration: 3000,
        mask: true
      });
      return null;
    }
  }
  return response.data;
}

module.exports = {
  //上传token
  uploadToken: () => {return request('get', 'upload/token')},
  //版块分类列表
  listForumTaxonomy: () => {return request('get', 'forumtaxonomy')},
  //版块列表
  listForum: (params) => {return request('get', 'forum', params)},

  //话题列表
  listTopic: (params) => {return request('get', 'topic', params)},
  //话题创建
  createTopic: (params) => {return request('post', 'topic', params)},

  //回复列表
  listComment: (params) => {return request('get', 'comment', params)},
  //回复创建
  createComment: (params) => {return request('post', 'comment', params)},
  //回复的回复列表
  listCommentComment: (params) => {return request('get', 'comment/comment/list', params)},

  //我的-首页
  my: (params) => {return request('get', 'user', params)}
}